﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using HugMe.Bussiness.Model.vk;

namespace HugMe.Bussiness
{
	public static class Vk
	{
		public const string VkUserIdCookie = "vk.viewer_id";

		public static Person[] GetFriends(string meId, int page)
		{
			int pageSize = 8;

			var param = new Dictionary<string, object>
				                 {
					                 {"count", pageSize.ToString(CultureInfo.InvariantCulture)}, 
					                 {"offset", ((page - 1) * pageSize).ToString(CultureInfo.InvariantCulture)}, 

					                 {"order", "name"}, 
													 {"fields", "city,country,domain,sex,photo_100"}
				                 };



			param.Add("uid", meId);

			return Request<VkArrayResponse<Person>>("friends.get", param).Response;
		}

		public static void FillPartners(List<Person> model)
		{
			model = model ?? new List<Person>();
			var param = new Dictionary<string, object>
				                 {
													 {"fields", "city,country,sex,photo_50"}
				                 };

			StringBuilder sb = new StringBuilder();
			foreach (var person in model)
			{
				sb.Append(person.UserId + ",");
			}

			param.Add("uids", sb.ToString());
			var request = Request<VkArrayResponse<Person>>("users.get", param);
			Person[] response = null;
			if (request != null)
				response = request.Response;

			if (response != null)
				foreach (var person in response)
				{
					var list = model.Where(x => x.UserId == person.UserId).ToList();
					foreach (var person1 in list)
					{
						person1.FirstName = person.FirstName;
						person1.LastName = person.LastName;
						person1.PhotoUrlSmall = person.PhotoUrlSmall;
					}
				}
		}


		public static string GetParams(Dictionary<string, object> values)
		{
			StringBuilder sb = new StringBuilder();

			foreach (var pair in values)
			{
				sb.AppendFormat("{0}={1}&", pair.Key, HttpUtility.UrlEncode(pair.Value.ToString()));
			}

			return sb.ToString().TrimEnd('&');
		}

		private static T Request<T>(string method, Dictionary<string, object> parameters)
		{
			string data = GetParams(parameters);
			string url = "https://api.vk.com/method/" + method;

			WebRequest reqPost = WebRequest.Create(url);

			reqPost.Method = "POST";
			reqPost.Timeout = 120000;
			reqPost.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

			ServicePointManager.Expect100Continue = false;

			byte[] sentData = Encoding.UTF8.GetBytes(data);
			reqPost.ContentLength = sentData.Length;

			/*Stream sendStream*/
			Task<Stream> sendStreamTask = reqPost.GetRequestStreamAsync();
			// Выполняем запрос

			var sendStream = sendStreamTask.Result;

			sendStream.Write(sentData, 0, sentData.Length);
			sendStream.Flush();
			sendStream.Close();

			// Получаем результат
			using (var responseTask = reqPost.GetResponseAsync())
			{
				using (Stream responseStream = responseTask.Result.GetResponseStream())
				{
					using (StreamReader reader = new StreamReader(responseStream))
					{
						byte[] request = Encoding.UTF8.GetBytes(reader.ReadToEnd());
						using (MemoryStream ms = new MemoryStream(request))
						{
							DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
							T readObject = (T)ser.ReadObject(ms);

							return readObject;
						}
					}
				}
			}
		}

	}
}